package com.hainabo.mgcmall.api;

import com.hainabo.bootside.core.common.ReturnVO;
import com.hainabo.mgcmall.dao.DataDictOptionRepository;
import com.hainabo.mgcmall.dao.DataDictRepository;
import com.hainabo.mgcmall.dao.DyFormAttrRepository;
import com.hainabo.mgcmall.dao.DyFormRepository;
import com.hainabo.mgcmall.model.DataDict;
import com.hainabo.mgcmall.model.DataDictOption;
import com.hainabo.mgcmall.model.DyForm;
import com.hainabo.mgcmall.model.DyFormAttr;
import com.hainabo.mgcmall.util.DataTablePageUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.List;

@Api(value = "/v1/dyForm")
@Component
@Path("/v1/dyForm")
@Produces(MediaType.APPLICATION_JSON)
@Slf4j
public class DyFormResource {
	
	@Autowired
	DyFormRepository formRepository;
	@Autowired
	DyFormAttrRepository attrRepository;
	@Autowired
	JdbcTemplate jdbcTemplate;

	// 查询表单列表
	@GET
	@Path("/list")
	public DataTablePageUtil list(@Context HttpServletRequest request) {
		DataTablePageUtil dataTablePageUtil = new DataTablePageUtil(request);
		String formId = request.getParameter("formId");
		String formName = request.getParameter("formName");
		String status = StringUtils.isNotBlank(request.getParameter("status")) ? request.getParameter("status") : "1";
		String start = request.getParameter("start");
		String length = request.getParameter("length");

		StringBuilder sb = new StringBuilder();
		sb.append(
				" SELECT t.form_id formId,t.form_name formName,t.status FROM t_dy_form t WHERE 1=1");
		if (StringUtils.isNotBlank(formId)) {
			sb.append(" AND t.form_id = " + formId);
		}
		if (StringUtils.isNotBlank(formName)) {
			sb.append(" AND t.form_name = " + formName);
		}
		if (StringUtils.isNotBlank(status)) {
			sb.append(" AND t.status = " + status);
		}
		sb.append(" ORDER BY t.form_id");
		String countSql = "select count(*) totalNum from (" + sb.toString() + ") t";
		if (StringUtils.isNotBlank(start) && StringUtils.isNotBlank(length)) {
			sb.append(" limit " + start + "," + length);
		}
		List rows = jdbcTemplate.queryForList(sb.toString());
		dataTablePageUtil.setData(rows);
		int count = Integer.parseInt(jdbcTemplate.queryForList(countSql).get(0).get("totalNum").toString());
		dataTablePageUtil.setRecordsTotal(count);
		dataTablePageUtil.setRecordsFiltered(count);
		return dataTablePageUtil;
	}

	// 查询单个表单
	@GET
	@Path("/get/{formId}")
	public ReturnVO findById(@PathParam(value = "formId") Long formId) {
		return new ReturnVO(formRepository.findOne(formId));
	}

	// 删除表单
	@DELETE
	@Path("/del/{formId}")
	public ReturnVO del(@PathParam("formId") Long formId) {
		DyForm form = formRepository.findOne(formId);
		if (form != null) {
			form.setStatus(-1);
			formRepository.save(form);
			return new ReturnVO("删除成功");
		} else {
			return new ReturnVO(false, "没有找到要删除的数据");
		}
	}

	// 保存表单
	@POST
	@Path("/save")
	public ReturnVO save(DyForm form) {
		if (form.getFormId() != null) { // 更新
			DyForm old = formRepository.findOne(form.getFormId());
			// 1.前端更改的是formName
			if (form.getFormName() != null) {
				List<DyForm> existList = formRepository.findByFormName(form.getFormName());
				if (existList.size() > 1
						|| (existList.size() == 1 && existList.get(0).getFormId() != form.getFormId())) {
					return new ReturnVO(0, null, "已经存在相同的表单名称，请重新输入");
				}
				old.setFormName(form.getFormName());// 只更新formName
			}
			return new ReturnVO(formRepository.save(old));
		} else { // 新增
			List<DyForm> existList = formRepository.findByFormName(form.getFormName());
			if (!existList.isEmpty()) {
				return new ReturnVO(0, null, "已经存在相同的表单名称，请重新输入");
			}
			form.setStatus(1);
			return new ReturnVO(formRepository.save(form));
		}
	}

	// 查询表单属性列表
	@GET
	@Path("/attr/list/{formId}")
	public DataTablePageUtil attrList(@Context HttpServletRequest request, @PathParam("formId") Long formId) {
		DataTablePageUtil dataTablePageUtil = new DataTablePageUtil(request);
		String attrId = request.getParameter("attrId");
		String attrName = request.getParameter("attrName");
		String type = request.getParameter("type");
		String maxLength = request.getParameter("maxLength");
		String required = request.getParameter("required");
		String dictId = request.getParameter("dictId");
		String status = StringUtils.isNotBlank(request.getParameter("status")) ? request.getParameter("status") : "1";
		String start = request.getParameter("start");
		String length = request.getParameter("length");

		StringBuilder sb = new StringBuilder();
		sb.append(
				" SELECT t.attr_id attrId, t.attr_name attrName, t.type, t.max_length maxLength, t.required, t.form_id formId, t.dict_id dictId, t.status FROM t_dy_form_attr t WHERE 1 = 1 ");
		if (StringUtils.isNotBlank(attrId)) {
			sb.append(" AND t.attr_id = " + attrId);
		}
		if (StringUtils.isNotBlank(attrName)) {
			sb.append(" AND t.attr_name = " + attrName);
		}
		if (StringUtils.isNotBlank(type)) {
			sb.append(" AND t.type = " + type);
		}
		if (StringUtils.isNotBlank(maxLength)) {
			sb.append(" AND t.max_length = " + maxLength);
		}
		if (StringUtils.isNotBlank(required)) {
			sb.append(" AND t.required = " + required);
		}
		sb.append(" AND t.form_id = " + formId);
		if (StringUtils.isNotBlank(dictId)) {
			sb.append(" AND t.dict_id = " + dictId);
		}
		if (StringUtils.isNotBlank(status)) {
			sb.append(" AND t.status = " + status);
		}
		sb.append(" ORDER BY t.attr_id");
		String countSql = "select count(*) totalNum from (" + sb.toString() + ") t";
		if (StringUtils.isNotBlank(start) && StringUtils.isNotBlank(length)) {
			sb.append(" limit " + start + "," + length);
		}
		List rows = jdbcTemplate.queryForList(sb.toString());
		dataTablePageUtil.setData(rows);
		int count = Integer.parseInt(jdbcTemplate.queryForList(countSql).get(0).get("totalNum").toString());
		dataTablePageUtil.setRecordsTotal(count);
		dataTablePageUtil.setRecordsFiltered(count);
		return dataTablePageUtil;
	}

	// 保存表单属性
	@POST
	@Path("/attr/save")
	public ReturnVO attrSave(DyFormAttr attr) {
		if (attr.getAttrId() != null) { // 更新
			DyFormAttr old = attrRepository.findOne(attr.getAttrId());
			// 1.前端更改的是attrName
			if (attr.getAttrName() != null) {
				List<DyFormAttr> existList = attrRepository.findByAttrNameAndFormId(attr.getAttrName(),
						attr.getFormId());
				if (existList.size() > 1
						|| (existList.size() == 1 && existList.get(0).getAttrId() != attr.getAttrId())) {
					return new ReturnVO(0, null, "已经存在相同的属性名称，请重新输入");
				}
				old.setAttrName(attr.getAttrName());// 只更新attrName
			}
//			// 2.前端要更改的是optionValue
//			if (option.getOptionValue() != null) {
//				List<DataDictOption> existList = optionRepository.findByOptionValueAndDictId(option.getOptionValue(),
//						option.getDictId());
//				if (existList.size() > 1
//						|| (existList.size() == 1 && existList.get(0).getOptionId() != option.getOptionId())) {
//					return new ReturnVO(0, null, "已经存在相同的属性值，请重新输入");
//				}
//				old.setOptionValue(option.getOptionValue());// 只更新optionValue
//			}
			return new ReturnVO(attrRepository.save(old));
		} else { // 新增
			List existList = attrRepository.findByAttrNameAndFormId(attr.getAttrName(), attr.getFormId());
			if (!existList.isEmpty()) {
				return new ReturnVO(0, null, "该表单中已经存在相同的属性名称，请重新输入");
			}
			attr.setStatus(1);
			return new ReturnVO(attrRepository.save(attr));
		}
	}

	// 删除属性
	@DELETE
	@Path("/attr/del/{attrId}")
	public ReturnVO attrDel(@PathParam("attrId") Long attrId) {
		DyFormAttr attr = attrRepository.findOne(attrId);
		if (attr != null) {
			attr.setStatus(-1);
			attrRepository.save(attr);
			return new ReturnVO("删除成功");
		} else {
			return new ReturnVO(false, "没有找到要删除的数据");
		}
	}

}